package com.gzist.security4.domain;

import com.baomidou.mybatisplus.annotation.*;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * @TableName user
 * @Author: 黄泽建
 */
@TableName(value = "user")
@Data
@ApiModel("用户类")
public class User implements Serializable, UserDetails {
    /**
     * 用户id
     */
    @TableId(value = "id", type = IdType.AUTO)
    @ApiModelProperty("用户id")
    private Long id;

    /**
     * 用户账号
     */
    @TableField(value = "username")
    @ApiModelProperty("用户账号")
    private String username;

    /**
     * 用户密码
     */
    @TableField(value = "password")
    @ApiModelProperty("用户密码")
    @JsonIgnore // 查询的用户信息忽略密码
    private String password;

    /**
     * 用户昵称
     */
    @TableField(value = "nickname")
    @ApiModelProperty("用户昵称")
    private String nickname;

    /**
     * 用户邮箱
     */
    @TableField(value = "email")
    @ApiModelProperty("用户邮箱")
    private String email;

    /**
     * 用户是否被删除
     */
    @TableField(value = "deleted")
    @ApiModelProperty("用户是否被删除")
    @TableLogic
    private Integer deleted;

    /**
     * 用户创建时间
     */
    @TableField(value = "created_time")
    @ApiModelProperty("用户创建时间")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime createdTime;

    /**
     * 用户更新时间
     */
    @TableField(value = "updated_time")
    @ApiModelProperty("用户更新时间")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime updatedTime;

    @TableField(exist = false)
    private static final long serialVersionUID = 1L;

    //暂时存储权限信息
    @TableField(exist = false)
    @ApiModelProperty("当前用户拥有的权限标识")
    private List<String> perms = new ArrayList<>();

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (perms != null && perms.size() > 0) {
            //返回权限信息
            //注意，在这如果perms中存在空字符串的话，那么这里就会导致权限导不进去而报错
            return perms.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toSet());
        }
        return null;
    }

    @Override
    public boolean isAccountNonExpired() {
        return deleted == 0;
    }

    @Override
    public boolean isAccountNonLocked() {
        return deleted == 0;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return deleted == 0;
    }

    @Override
    public boolean isEnabled() {
        return deleted == 0;
    }
}